<script setup>
    import productApi from '@/api/product/product.js'
    import {ref, reactive} from 'vue'
    import {
        Delete,
        Edit,
    } from '@element-plus/icons-vue'
    import {ElMessage, ElMessageBox} from 'element-plus'

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const productQuery = reactive({
        name: '',
		category1Id: '',
		category2Id: '',
		category3Id: '',
        page: 1,
        limit: 10
    })
	//分类搜索条件
	const searchCategoryIdList = ref([])
	const searchCategoryProps = ref({
		value: 'id',
		label: 'name',
        checkStrictly: true, //选择任意一级选项
		lazy: true,
		lazyLoad(node, resolve) {
            //刚开始点击级联框，node.value == 'undefined'，
			//所有一级分类的父分类是0： node.value=0
            if (typeof node.value == 'undefined') {
                node.value = 0
			}
            categoryApi.selectByParentId(node.value).then(result => {
                if (result.code === 0) {
					const {data} = result
					data.forEach(categoryVO => {
                        categoryVO.leaf = !categoryVO.hasChildren
					})

					//返回数据
                    resolve(result.data)
				}
            })
		}
	})

    const loadData = () => {
        productApi.list(productQuery).then(result => {
            list.value = result.data.records
            total.value = result.data.total

			list.value.forEach((product) => {
                product.carouselImageList = product.carouselImage.split(',')
			})

        })
    }

    loadData()

    const onSearch = () => {
        //清空搜索条件里面之前的值
		productQuery.category1Id = ''
		productQuery.category2Id = ''
		productQuery.category3Id = ''

		if (searchCategoryIdList.value != undefined) {
            if (searchCategoryIdList.value.length == 1) {
                productQuery.category1Id = searchCategoryIdList.value[0]
            } else if (searchCategoryIdList.value.length == 2) {
                productQuery.category1Id = searchCategoryIdList.value[0]
                productQuery.category2Id = searchCategoryIdList.value[1]
            } else if (searchCategoryIdList.value.length == 3) {
                productQuery.category1Id = searchCategoryIdList.value[0]
                productQuery.category2Id = searchCategoryIdList.value[1]
                productQuery.category3Id = searchCategoryIdList.value[2]
            }
		}


        productQuery.page = 1
        loadData()
    }

    //根据id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            productApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    const ids = ref([])
    const handleSelectionChange = (rows) => {
        //console.log('多选', rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }

    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            productApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //添加、编辑
    const dialogFormVisible = ref(false)
    const product = ref({})
    const title = ref()
	//添加、编辑弹出框保存选择分类的id
	const categoryIdList = ref([])
    const categoryProps = ref({
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad(node, resolve) {
            //刚开始点击级联框，node.value == 'undefined'，
            //所有一级分类的父分类是0： node.value=0
            if (typeof node.value == 'undefined') {
                node.value = 0
            }
            categoryApi.selectByParentId(node.value).then(result => {
                if (result.code === 0) {
                    const {data} = result
                    data.forEach(categoryVO => {
                        categoryVO.leaf = !categoryVO.hasChildren
                    })

                    //返回数据
                    resolve(result.data)
                }
            })
        }
    })

    //因为取消了checkStrictly: true, //选择任意一级选项，这时候只有选中三个才会触发change事件
	const categoryChange = () => {
        product.value.category1Id = categoryIdList.value[0]
        product.value.category2Id = categoryIdList.value[1]
        product.value.category3Id = categoryIdList.value[2]
	}

    //轮播图
	const carouselList = ref([])
	/*const carouselImageList = ref([])
	const handleCarouselSuccess = (result, uploadFile) => {
		if (result.code == 0) {
            carouselImageList.value.push(result.data)
		}
	}
    const handleCarouselRemove = (uploadFile, uploadFiles) => {
        console.log(uploadFile, uploadFiles)
        carouselImageList.value.splice(carouselImageList.value.indexOf(uploadFile.url), 1)
	}*/

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        product.value = {}
        categoryIdList.value = []
        carouselList.value = []
    }

    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        product.value = {}
        carouselList.value = []
        productApi.selectById(id).then(result => {
            product.value = result.data

			//三级分类回显
            categoryIdList.value[0] = product.value.category1Id
            categoryIdList.value[1] = product.value.category2Id
            categoryIdList.value[2] = product.value.category3Id

			//轮播图回显
			carouselList.value = []
			const carouselImage = product.value.carouselImage.split(',')
            carouselImage.forEach(image => {
                carouselList.value.push({url : image})
			})
        })
    }

    const addOrUpdate = () => {
        //用逗号拼接轮播图字符串到：product.value.carouselImage
        const carouselImage = ref([])
        carouselList.value.forEach(item => {
            // blob:http://localhost:5175/27fe02fc-96e2-49f6-95a6-23cb876b4634
            //carouselImage.value.push(item.url.substring('blob:'.length))
			if (item.response) {//上传的图片
                carouselImage.value.push(item.response.data)
            } else {//数据库查找回显的
                carouselImage.value.push(item.url)
			}
        })
        product.value.carouselImage =  carouselImage.value.join(',')

        if (product.value.id) {//编辑
            productApi.update(product.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else {//添加
            //将carouselImageList集合保存的轮播图，用逗号拼接成字符串放到product的carouselImage
			//product.value.carouselImage =  carouselImageList.value.join(',')
			/*const carouselImage = ref([])
			carouselList.value.forEach(item => {
                // blob:http://localhost:5175/27fe02fc-96e2-49f6-95a6-23cb876b4634
				//carouselImage.value.push(item.url.substring('blob:'.length))
				carouselImage.value.push(item.response)
			})
            product.value.carouselImage =  carouselImage.value.join(',')*/

            productApi.add(product.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    import {Plus} from '@element-plus/icons-vue'

    const handleAvatarSuccess = (result) => {
        product.value.image = result.data
    }

    import {useTokenStore} from '@/store/token.js'
    import categoryApi from "@/api/product/category.js";
    const tokenStore = useTokenStore()
    const headers = ref({
		//添加token
		Authorization: tokenStore.token
	})

	//修改status状态
	const handleSwitchChange = (row) => {
        productApi.updateStatus(row.id, row.status).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
			} else {
                ElMessage.error(result.msg)
			}
		})
	}
</script>

<template>
	<el-card class="">
		<template #header>
			<div class="header">
				<el-button type="primary" @click="showAddDialog">添加</el-button>
				<el-button type="primary" @click="deleteAll">批量删除</el-button>
			</div>
		</template>
		<el-form :inline="true">
			<el-form-item label="名字">
				<el-input v-model="productQuery.name" placeholder="请输入名字" clearable/>
			</el-form-item>
			<el-form-item label="分类">
				<el-cascader
						clearable
						v-model="searchCategoryIdList"
						:props="searchCategoryProps"
						style="width: 100%" />
			</el-form-item>
			<el-form-item label="更新时间" :label-width="100">
				<el-date-picker
					v-model="productQuery.beginUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="开始时间"
				/>
				<el-date-picker
					v-model="productQuery.endUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="结束时间"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSearch">搜索</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55"/>
			<el-table-column fixed prop="id" label="ID"/>
			<el-table-column prop="name" label="名字"/>
			<el-table-column prop="category1Name" label="一级分类"/>
			<el-table-column prop="category2Name" label="二级分类"/>
			<el-table-column prop="category3Name" label="三级分类"/>
			<el-table-column prop="image" label="主图" #default="scope">
				<img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
			</el-table-column>
			<el-table-column
					prop="carouselImage"
					label="轮播图"
					#default="scope"
					width="200">
				<div style="height: 50px;float: left;">
					<img
							v-for="(item, index) in scope.row.carouselImageList"
							:key="index"
							:src="item"
							width="50"
					/>
				</div>
			</el-table-column>
			<el-table-column prop="status" label="状态">
				<template #default="scope">
					<el-switch
						v-model="scope.row.status"
						style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
						:active-value="1"
						:inactive-value="0"
						@change="handleSwitchChange(scope.row)"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="更新时间"/>
			<el-table-column fixed="right" label="Operations">
				<template #default="{ row }">
					<el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
					<el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
				v-model:current-page="productQuery.page"
				v-model:page-size="productQuery.limit"
				:page-sizes="[10, 20, 30, 40]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@change="loadData"
				style="margin-top: 20px; justify-content: flex-end"
		/>
	</el-card>


	<!--添加、编辑弹出框-->
	<el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
		<el-form :model="product">
			<el-form-item label="名字" :label-width="60">
				<el-input v-model="product.name" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="分类" :label-width="60">
				<el-cascader
						v-model="categoryIdList"
						:props="categoryProps"
						@change="categoryChange"
						style="width: 100%" />
			</el-form-item>
			<el-form-item label="主图" :label-width="60">
				<el-upload
					class="avatar-uploader"
					action="/api/product/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:headers="headers"
					>
					<img v-if="product.image" :src="product.image" class="avatar"/>
					<el-icon v-else class="avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item  label="轮播图" :label-width="60">
				<el-upload
					v-model:file-list="carouselList"
					action="/api/product/upload"
					list-type="picture-card"
					:on-success="handleCarouselSuccess"
					:on-remove="handleCarouselRemove"
				>
					<el-icon><Plus /></el-icon>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="addOrUpdate">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>
